package net.sansi.v3correctserver.entity.image;

import lombok.Getter;
import lombok.Setter;
import net.sansi.v3correctserver.entity.IntPoint;
import net.sansi.v3correctserver.entity.color.PhotoColor;
import net.sansi.v3correctserver.exception.ServiceException;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.nio.file.Path;

/**
 * Created by Fang
 * create time : 2024/11/5
 * IDE : IntelliJ IDEA
 * <p>
 * 常规照片对象，jpeg png bmp 等
 */
@Getter
@Setter
public class RecCmmImage extends RecImageBase {

    private final BufferedImage image;

    private RecImage blackImage;

    /**
     * 加载照片
     *
     * @param path 照片路径
     */
    public RecCmmImage(Path path) {
        this(path, null);
    }

    public RecCmmImage(Path path, RecImage blackImage) {
        try {
            setPath(path);
            image = ImageIO.read(path.toFile());
            this.blackImage = blackImage;
        } catch (Exception e) {
            throw new ServiceException("读取照片异常 {}", path.toFile().getAbsoluteFile(), e);
        }
    }

    /**
     * 创建一张空的照片
     *
     * @param width  宽度
     * @param height 高度
     */
    public RecCmmImage(int width, int height) {
        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    }

    @Override
    public int getWidth() {
        return image.getWidth();
    }

    @Override
    public int getHeight() {
        return image.getHeight();
    }

    @Override
    public PhotoColor getPhotoColor(int x, int y) {
        int color = image.getRGB(x, y);
        PhotoColor pc = new PhotoColor(new Color(color));
        if (blackImage != null) {
            pc = pc.minus(blackImage.getPhotoColor(x, y));
        }
        return pc;
    }

    @Override
    public void save(Path path) {
        try {
            ImageIO.write(image, "png", path.toFile());
        } catch (Exception e) {
            throw new ServiceException("保存照片异常 {}", path.toFile().getAbsoluteFile(), e);
        }
    }

    @Override
    public void setColor(int x, int y, PhotoColor color) {
        image.setRGB(x, y, color.toColor().getRGB());
    }

    @Override
    public void writeText(IntPoint startPoint, String text, PhotoColor color) {
        Graphics2D g2d = image.createGraphics();
        g2d.setColor(color.toColor());
        Font font = new Font("Microsoft YaHei", Font.PLAIN, 12);
        g2d.setFont(font);
        g2d.drawString(text, startPoint.getX(), startPoint.getY());
        g2d.dispose();
    }
}
